package cn.tedu.mall.seckill.init;

import cn.tedu.mall.pojo.seckill.vo.SeckillSkuVO;
import cn.tedu.mall.pojo.seckill.vo.SeckillSpuVO;
import cn.tedu.mall.seckill.mapper.SeckillSkuMapper;
import cn.tedu.mall.seckill.mapper.SeckillSpuMapper;
import cn.tedu.mall.seckill.service.impl.SeckillSkuServiceImpl;
import cn.tedu.mall.seckill.service.impl.SeckillSpuServiceImpl;
import cn.tedu.mall.seckill.util.RedisBloomUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Random;

@Component
@Slf4j
public class SeckillInitializer {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SeckillSpuMapper seckillSpuMapper;
    @Autowired
    private SeckillSkuMapper seckillSkuMapper;

    public void initStart(){
        initSpus();
    }
    @Autowired
    private RedisBloomUtils redisBloomUtils;
    private void initSpus(){
        List<SeckillSpuVO> seckillSpuVOS = seckillSpuMapper.selectAll();
        if (seckillSpuVOS==null || seckillSpuVOS.size()==0){
            log.error("当前数据库没有spu预热的数据,请检查数据库");
            return;
        }
        ValueOperations valueOperations = redisTemplate.opsForValue();
        valueOperations.set(SeckillSpuServiceImpl.SECKILL_SPUS_KEY,seckillSpuVOS);
        for (SeckillSpuVO seckillSpuVO : seckillSpuVOS) {
            Long spuId = seckillSpuVO.getId();
            redisBloomUtils.bfadd(SeckillSpuServiceImpl.SECKILL_BLOOM_SPUS_KEY,spuId+"");
            String url = "/seckill/"+(new Random().nextInt(9000)+1000);
            seckillSpuVO.setUrl(url);
            valueOperations.set(SeckillSpuServiceImpl.SECKILL_SPU_PREFIX+spuId,seckillSpuVO);

            initSkus(spuId);
        }
    }

    private void initSkus(Long spuId){
        //从数据库先查询sku select * from seckill_sku where spu_id=#{spuId}
        List<SeckillSkuVO> seckillSkuVOS=seckillSkuMapper.selectSkuBySpuId(spuId);
        if (seckillSkuVOS==null||seckillSkuVOS.size()==0){
            log.error("秒杀sku数据为空,请检查数据库");
            return;
        }
        //放到预热的缓存中
        ValueOperations valueOperations = redisTemplate.opsForValue();
        String skusKey= SeckillSkuServiceImpl.SECKILL_SKUS_PREFIX+spuId;
        valueOperations.set(skusKey,seckillSkuVOS);
    }
}
